
import 'dart:async';
import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:ayj_flutter_chat_app/common/configs/project_config.dart';
import 'package:flutter/cupertino.dart';
import 'package:jhtoast/jhtoast.dart';

class AudioPlayerManager extends GetxController{

  final AudioPlayer _audioPlayer = AudioPlayer();

  PlayerState? _playerState;
  Duration? _duration;
  Duration? _position;
  String? _url;

  StreamSubscription? _durationSubscription;
  StreamSubscription? _positionSubscription;
  StreamSubscription? _playerCompleteSubscription;
  StreamSubscription? _playerStateChangeSubscription;


  String? get url => _url;

  bool get isPlaying => _playerState == PlayerState.playing;

  bool get isPaused => _playerState == PlayerState.paused;

  String get durationText => _duration?.toString().split('.').first ?? '';

  String get positionText => _position?.toString().split('.').first ?? '';

  AudioPlayer get player => _audioPlayer;


  void _setConfig({ReleaseMode? model,String? url}){
    if(url != null){
      _url = url;
    }

    if(model != null){
      // Set the release mode to keep the source after playback has completed.
      player.setReleaseMode(model ?? ReleaseMode.stop);
    }

  }

  @override
  void onInit() {
    super.onInit();
    // Use initial values from player
    _playerState = player.state;

    _initStreams();

    // Start the player as soon as the app is displayed.
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if(_url != null){
        // await _audioPlayer.load(Uri.parse(_url??''));
        // File audioFile = File(_url ?? '');
        // String localPath = audioFile.path;
        await _audioPlayer.play(DeviceFileSource(_url??''));
      }
    });

  }

  @override
  void dispose() {
    _durationSubscription?.cancel();
    _positionSubscription?.cancel();
    _playerCompleteSubscription?.cancel();
    _playerStateChangeSubscription?.cancel();
    super.dispose();
  }


  void _initStreams() {
    _durationSubscription = player.onDurationChanged.listen((duration) {
      _duration = duration;
    });

    _positionSubscription = player.onPositionChanged.listen(
          (p) => _position = p,
    );

    _playerCompleteSubscription = player.onPlayerComplete.listen((event) {
      _playerState = PlayerState.stopped;
      _position = Duration.zero;
    });

    _playerStateChangeSubscription =
        player.onPlayerStateChanged.listen((state) {
          _playerState = state;
        });
  }

  Future<void> seek(BuildContext context,int milliseconds)async {
    if(_url == null){
      JhToast.showText(context, msg: '没有播放地址');
      return;
    }
    player.seek(Duration(milliseconds: milliseconds));
  }

  Future<void> play(context,{ReleaseMode? model,String? url}) async {
    if(url == null && _url == null){
      JhToast.showText(context, msg: '没有播放地址');
      return;
    }
    _setConfig(model: model,url: url);
    await _audioPlayer.play(DeviceFileSource(_url??''));
    // await player.resume();
    _playerState = PlayerState.playing;
  }

  Future<void> pause() async {
    await player.pause();
    _playerState = PlayerState.paused;
  }

  // Future<Duration> getAudioDuration(String url) async {
  //   AudioCache cache = AudioCache();
  //   // 加载音频文件，但不播放
  //   await cache.load(url);
  //
  //   // 获取音频时长
  //   return cache.play(url);
  // }

  Future<void> stop() async {
    await player.stop();
    _playerState = PlayerState.stopped;
    _position = Duration.zero;
  }
}